package com.yudean.esb.security.impl;

import cn.hutool.core.util.StrUtil;
import com.yudean.esb.common.Constants;
import com.yudean.esb.common.ServiceConstant;
import com.yudean.esb.security.SecurtiyChecker;
import com.yudean.esb.util.SecurityTools;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * @author DL<duanlei@gdyd.com>
 * @version V1.0
 * @date 13-8-27 上午11:15
 */
@Service("securtiyChecker")
@Scope("prototype")
@Slf4j
public class SecurtiyChekerImpl implements SecurtiyChecker {
    @Getter
    private String errorMsg;
    @Getter
    private String errorCode;

    /**
     * 权限校验
     * add by szq
     * @param serviceID 定义的服务的唯一标示
     * @param token 安全令牌
     * @return boolean
     */
    @Override
    public boolean validate(String serviceID, String token) {
        boolean isValid = true;
        //校验token
        if (token == null || "".equals(token.trim())) {
            errorMsg = "token不能为空";
            errorCode = Constants.CODE_AUTH_ERROR_MSG;
            isValid = false;
            log.error("token数据为空");
        }else if(getUserInfo(token) == null){
            errorMsg = "非法token";
            errorCode = Constants.CODE_AUTH_ERROR_MSG;
            isValid = false;
            log.error("token：{}有误",token);
        }
        //检验serviceID
        if (StrUtil.hasEmpty(serviceID)) {
            errorCode = Constants.CODE_CLIENT_ERROR;
            errorMsg = "serviceID不能为空";
            isValid = false;
            log.error("serviceID为空");
        } else if (!ServiceConstant.SERVICE_IDS.contains(serviceID)) {
            errorCode = Constants.CODE_CLIENT_ERROR;
            errorMsg = "非法serviceID";
            isValid = false;
            log.error("serviceID：{}有误",serviceID);
        }
        return isValid;
    }
    @Override
    public boolean verifyID(String id) {
        if (id == null || "".equals(id)) {
            return false;
        }
        return SecurityTools.verifyUUID(id.trim());
    }

    @Override
    public String[] getUserInfo(String token) {
        String decoded = decode(token);
        if (decoded == null) {
            return null;
        }
        return decoded.split("#");
    }

    @Override
    public String decode(String token) {
        if (token == null || "".equals(token.trim())) {
            return null;
        }
        String decrypted = null;
        try {
            decrypted = SecurityTools.decrypt(token.trim());
        } catch (Exception e) {
            return null;
        }
        return decrypted;
    }
}
